<template>
  <div class="streaming-test p-6 bg-gray-50 rounded-lg">
    <h3 class="text-lg font-semibold mb-4">🧪 流式数据显示测试</h3>
    
    <div class="test-controls mb-6 space-y-4">
      <button 
        @click="startStreamingTest"
        :disabled="isStreaming"
        class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"
      >
        {{ isStreaming ? '正在流式输出...' : '开始流式测试' }}
      </button>
      
      <div class="flex gap-4">
        <label class="flex items-center gap-2">
          <span>速度:</span>
          <select v-model="streamSpeed" class="border rounded px-2 py-1">
            <option value="50">快速 (50ms)</option>
            <option value="100">正常 (100ms)</option>
            <option value="200">慢速 (200ms)</option>
          </select>
        </label>
        
        <label class="flex items-center gap-2">
          <span>测试文本:</span>
          <select v-model="testTextType" class="border rounded px-2 py-1">
            <option value="simple">简单文本</option>
            <option value="markdown">Markdown格式</option>
            <option value="chinese">中文长文本</option>
          </select>
        </label>
      </div>
    </div>
    
    <!-- 流式消息显示区域 -->
    <div class="streaming-display border rounded-lg p-4 bg-white min-h-[200px]">
      <div class="message-header mb-2">
        <span class="text-sm text-gray-500">AI助手</span>
        <span v-if="isStreaming" class="ml-2 text-xs text-blue-500">● 正在输入</span>
      </div>
      
      <div 
        class="message-content text-gray-900 leading-relaxed"
        :class="{ 'streaming': isStreaming }"
      >
        <div v-html="displayedContent"></div>
        <span v-if="isStreaming" class="streaming-cursor">|</span>
      </div>
      
      <div v-if="isStreaming" class="progress-bar mt-4">
        <div class="w-full bg-gray-200 rounded-full h-2">
          <div 
            class="bg-blue-500 h-2 rounded-full transition-all duration-300"
            :style="{ width: `${progress}%` }"
          ></div>
        </div>
        <div class="text-xs text-gray-500 mt-1">
          进度: {{ Math.round(progress) }}% ({{ currentIndex }}/{{ totalLength }})
        </div>
      </div>
    </div>
    
    <!-- 测试结果 -->
    <div v-if="testResults.length > 0" class="test-results mt-6">
      <h4 class="font-medium mb-2">测试结果:</h4>
      <div class="space-y-2">
        <div 
          v-for="(result, index) in testResults" 
          :key="index"
          class="text-sm p-2 bg-white rounded border"
        >
          <div class="flex justify-between">
            <span>{{ result.type }}</span>
            <span class="text-gray-500">{{ result.duration }}ms</span>
          </div>
          <div class="text-xs text-gray-400">{{ result.timestamp }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const isStreaming = ref(false)
const displayedContent = ref('')
const currentIndex = ref(0)
const totalLength = ref(0)
const streamSpeed = ref(100)
const testTextType = ref('simple')
const testResults = ref<Array<{
  type: string
  duration: number
  timestamp: string
}>>([])

const testTexts = {
  simple: '这是一个简单的流式文本测试。我们正在验证文字是否能够逐字显示，就像真实的AI对话一样。',
  markdown: '# 流式Markdown测试\n\n这是一个**粗体文本**和*斜体文本*的测试。\n\n```javascript\nconsole.log("代码块测试");\n```\n\n- 列表项1\n- 列表项2\n- 列表项3',
  chinese: '在人工智能快速发展的今天，实时流式数据传输已经成为现代聊天应用的核心功能。通过Server-Sent Events (SSE)技术，我们可以实现真正的实时通信体验。用户不再需要等待完整的响应，而是可以看到AI助手的思考过程和逐步生成的回答。这种技术不仅提升了用户体验，也让人机交互变得更加自然和流畅。'
}

const progress = computed(() => {
  if (totalLength.value === 0) return 0
  return (currentIndex.value / totalLength.value) * 100
})

const startStreamingTest = async () => {
  if (isStreaming.value) return
  
  const startTime = Date.now()
  isStreaming.value = true
  displayedContent.value = ''
  currentIndex.value = 0
  
  const testText = testTexts[testTextType.value as keyof typeof testTexts]
  totalLength.value = testText.length
  
  // 模拟流式数据传输
  for (let i = 0; i <= testText.length; i++) {
    if (!isStreaming.value) break // 允许中断
    
    currentIndex.value = i
    displayedContent.value = testText.substring(0, i)
    
    // 处理Markdown格式
    if (testTextType.value === 'markdown') {
      displayedContent.value = formatMarkdown(displayedContent.value)
    }
    
    await new Promise(resolve => setTimeout(resolve, Number(streamSpeed.value)))
  }
  
  const endTime = Date.now()
  isStreaming.value = false
  
  // 记录测试结果
  testResults.value.unshift({
    type: `${testTextType.value} (${streamSpeed.value}ms)`,
    duration: endTime - startTime,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 保持最近10次测试结果
  if (testResults.value.length > 10) {
    testResults.value = testResults.value.slice(0, 10)
  }
}

const formatMarkdown = (text: string) => {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`([^`]+)`/g, '<code class="bg-gray-100 px-1 rounded">$1</code>')
    .replace(/```([\s\S]*?)```/g, '<pre class="bg-gray-100 p-2 rounded mt-2"><code>$1</code></pre>')
    .replace(/^# (.*$)/gm, '<h1 class="text-xl font-bold mt-4 mb-2">$1</h1>')
    .replace(/^## (.*$)/gm, '<h2 class="text-lg font-semibold mt-3 mb-2">$1</h2>')
    .replace(/^- (.*$)/gm, '<li class="ml-4">• $1</li>')
    .replace(/\n/g, '<br>')
}
</script>

<style scoped>
.streaming-cursor {
  @apply text-blue-500 font-bold ml-1;
  animation: blink 1s infinite;
}

.message-content.streaming {
  position: relative;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

.message-content :deep(code) {
  @apply bg-gray-100 px-1 py-0.5 rounded text-sm font-mono;
}

.message-content :deep(pre) {
  @apply bg-gray-100 p-3 rounded-lg overflow-x-auto mt-2;
}

.message-content :deep(h1) {
  @apply text-xl font-bold mt-4 mb-2;
}

.message-content :deep(h2) {
  @apply text-lg font-semibold mt-3 mb-2;
}

.message-content :deep(li) {
  @apply ml-4 list-none;
}
</style> 